import { AssistantDetail } from '@/types/assistant'
import { create } from 'zustand'
import { getAssistantDetailApi } from '../controllers/API/assistant'

/**
 * 助手编辑管理
 */

type State = {
  changed: boolean
  assistantState: AssistantDetail
  toolList: any[]
}

type Action =
  | 'setBaseInfo'
  | 'setting'
  | 'setPrompt'
  | 'setGuideword'
  | 'setTools'
  | 'setFlows'
  | 'setQuestion'
  | 'setDesc'

type Actions = {
  dispatchAssistant: (action: Action, assistantState: Partial<AssistantDetail>) => void
  dispatchToolList: (action: Action, data: any[]) => void
  loadAssistantState: (id: string) => Promise<any>
  chatloadAssistantState: (data: any) => Promise<any>
  saveAfter: () => void
  destroy: () => void
}

const assistantReducer = (state: State, action: Action, data: Partial<AssistantDetail>) => {
  console.log('action :>> ', action, data)
  return { changed: true, assistantState: { ...state.assistantState, ...data } }
}

const toolListReducer = (state: State, action: Action, data: any[]) => {
  console.log('toolList action :>> ', action, data)
  return { toolList: data }
}

const assistantTemp = {
  id: 3,
  name: '',
  desc: '',
  logo: '',
  prompt: '',
  guide_word: '',
  guide_question: [],
  model_name: '',
  temperature: 0.5,
  status: 0,
  user_id: 1,
  create_time: '',
  update_time: '',
  tool_id: '',
  tool_list: [],
  flow_list: [],
  knowledge_list: [],
  role_save_judgment: ''
}

export const useAssistantStore = create<State & Actions>(set => ({
  changed: false,
  assistantState: { ...assistantTemp },
  toolList: [],
  dispatchAssistant: (action: Action, data: Partial<AssistantDetail>) =>
    set(state => assistantReducer(state, action, data)),
  dispatchToolList: (action: Action, data: any[]) => set(state => toolListReducer(state, action, data)),
  // 加载助手状态
  loadAssistantState: id => {
    return getAssistantDetailApi(id).then(data => {
      set({
        assistantState: {
          ...data,
          // 补一个空行
          guide_question: data.guide_question ? [...data.guide_question, ''] : ['']
          // guide_question: data.guide_question
          // ? data.guide_question.length < 10
          //   ? [...data.guide_question, '']
          //   : [...data.guide_question]
          // : ['']
        }
      })
      return data
    })
  },
  // chat 兼容之前逻辑
  chatloadAssistantState: data => {
    set({
      assistantState: {
        ...data,
        guide_question: data.guide_question ? [...data.guide_question, ''] : ['']
      }
    })
    return data
  },
  saveAfter() {
    set({ changed: false })
  },
  destroy: () => {
    set({ assistantState: { ...assistantTemp } })
  }
}))
